package com.sunjy.common.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sunjy.common.domain.ApiResponseT;
import com.sunjy.common.domain.HeaderEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class InvokeContext<T> {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(InvokeContext.class);
	private List<FilterAction> actions;
	private int index;
	private T param;
	private  HttpServletResponse response;
	private  HttpServletRequest request;
	
	
	
	

	public InvokeContext(List<FilterAction> actions, HttpServletResponse response,HttpServletRequest request) {
		super();
		this.actions = actions;
		this.response = response;
		this.request=request;
	}
	
	


	public HttpServletResponse getResponse() {
		return response;
	}




	public HttpServletRequest getRequest() {
		return request;
	}




	public T getParam() {
		return param;
	}

	public void setParam(T param) {
		this.param = param;
	}

	public boolean startInvoke() {
		reset();
		ApiResponseT<Object> result = invokeNext();
		if(result!=null){
			try {
				response.setHeader("Content-Type", "text/html;charset=UTF-8");
				response.getWriter().write(JSON.toJSONString(result));
				return false;
			} catch (IOException e) {
			}
		}
		
		return true;
	}

	/**
	 * 重置链
	 */
	public void reset() {
		this.index = 0;
	}

	/**
	 * 链传递 <br>
	 * 异常处理： 任何一个任务执行产生异常，发送异常信息给调用端
	 */
	public ApiResponseT<Object>  invokeNext() {
		if (actions != null && !actions.isEmpty()) {
			try {
				if (index <= actions.size() - 1) {
					FilterAction action = actions.get(index);
					index++;
					ApiResponseT<Object> invokeResult = action.invoke(this);
					
					return invokeResult;
				}
			} catch (Exception e) {
				LOGGER.error("", e);
				return ApiResponseT.error(HeaderEnum.SERVICE_MSG);
			}
		}
		
		return null;
	}
	
	public boolean startPostInvoke(Object rst) {
		reset();
		ApiResponseT<Object> result = postInvoke(rst);
		if(result!=null){
			try {
				response.getWriter().write(JSON.toJSONString(result));
				return false;
			} catch (IOException e) {
			}
		}
		
		return true;
	}


	public ApiResponseT<Object> postInvoke(Object rst) {
		if (actions != null && !actions.isEmpty()) {
			try {
				if (index <= actions.size() - 1) {
					FilterAction action = actions.get(index);
					index++;
					ApiResponseT<Object> invokeResult = action.after(this,rst);
					return invokeResult;
				}
			} catch (Exception e) {
				LOGGER.error("", e);
				return ApiResponseT.error(HeaderEnum.SERVICE_MSG);
			}
		}
		
		return null;
		
	}

}
